//
//  SS_WeChatNewsViewController.swift
//  SSNews
//
//  Created by 叶竞泽 on 2017/5/1.
//  Copyright © 2017年 叶竞泽. All rights reserved.
//

import UIKit
import AXWebViewController
import MJRefresh

fileprivate let wechatCellIdentifier = "wechatCellIdentifier"

class SS_WeChatNewsViewController: UIViewController {
    
    // MARK: - 属性
    
    /// 当前数据分页
    var currentPage = 1
    
    
    var dataList: [WeChatData]? = [WeChatData]() {
        didSet {
            wechatNewsTableView?.reloadData()
            refreshControlForHeader?.endRefreshing()
            refreshControlForFooter?.endRefreshing()
        }
    }
    
    var wechatNewsTableView: UITableView?
    
    lazy var refreshControlForHeader: MJRefreshNormalHeader? = {
        let header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(downRefresh))
        header?.setTitle("下拉刷新", for: MJRefreshState.idle)
        header?.setTitle("放开开始刷新", for: MJRefreshState.pulling)
        header?.setTitle("正在刷新", for: MJRefreshState.refreshing)
        header?.setTitle("没有更新的数据", for: MJRefreshState.noMoreData)
        return header
    }()
    lazy var refreshControlForFooter: MJRefreshAutoNormalFooter? = {
        let footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(upRefresh))
        footer?.setTitle("上拉刷新", for: MJRefreshState.idle)
        footer?.setTitle("放开开始刷新", for: MJRefreshState.pulling)
        footer?.setTitle("正在刷新", for: MJRefreshState.refreshing)
        footer?.setTitle("没有更新的数据", for: MJRefreshState.noMoreData)
        return footer
    }()
    
    // MARK: - 方法
    
    private func loadData() {
        
        var params = ["key": wechatAPPKey]
        params["pno"] = "\(currentPage)"
        
        SS_Network.shared.request(method: .GET, urlString: wechatAPI, parameters: params, progress: { (progress) in
        }, success: { (dataTask, json) in
            var dataList = json as? [String: Any]
            let result = dataList?["result"] as? [String: Any]
            let list = WeChatNewsResult.yy_model(with: result!)
            var tempArr = self.dataList
            for data in list!.list! {
                tempArr?.append(data)
            }
            self.dataList = tempArr
        }) { (dataTask, error) in
            print(error)
        }
    }
    
    @objc fileprivate func downRefresh() {
        currentPage = 1
        loadData()
    }
    
    @objc fileprivate func upRefresh() {
        currentPage += 1
        loadData()
    }
    
    // MARK: - 生命周期
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        loadData()
    }
}

// MARK: - 设置界面
extension SS_WeChatNewsViewController {
    
    fileprivate func setupUI() {
        title = "微信精选"
        setupTableView()
    }
    
    fileprivate func setupTableView() {
        wechatNewsTableView = UITableView(frame: view.bounds)
        wechatNewsTableView?.dataSource = self
        wechatNewsTableView?.delegate = self
        wechatNewsTableView?.register(UINib(nibName: "SS_WechatCell", bundle: nil), forCellReuseIdentifier: wechatCellIdentifier)
        wechatNewsTableView?.rowHeight = UITableViewAutomaticDimension
        wechatNewsTableView?.estimatedRowHeight = 100
        wechatNewsTableView?.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0)
        wechatNewsTableView?.mj_header = refreshControlForHeader
        wechatNewsTableView?.mj_footer = refreshControlForFooter
        view.addSubview(wechatNewsTableView!)
    }
}

extension SS_WeChatNewsViewController: UITableViewDataSource, UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        // FIXME: - 拿到最后一个cell
        
        
        
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if dataList == nil {
            return 1
        }
        return dataList!.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: wechatCellIdentifier, for: indexPath) as? SS_WechatCell
        if dataList != nil {
            cell?.data = dataList?[indexPath.row]
        }
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at: indexPath) as? SS_WechatCell
        guard let url = cell?.data?.url else {
            return
        }
        let webVC = AXWebViewController(address: url)
        navigationController?.pushViewController(webVC, animated: true)
    }
}
